package com.jyw.router.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.codec.Base64;
import com.jyw.router.common.core.domain.CommonResult;
import com.jyw.router.common.exception.ServiceException;
import com.jyw.router.hospital.domain.HospitalInfo;
import com.jyw.router.hospital.service.IHospitalInfoService;
import com.jyw.router.miniapp.domain.dto.CreateWxCodeDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@AllArgsConstructor
@RequestMapping("/wx/miniapp/code")
@Slf4j
@Api(tags = "小程序码")
public class WxCodeController {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private IHospitalInfoService hospitalService;

    @PostMapping
    @ApiOperation(value = "生成小程序码")
    public CommonResult<String> code(@RequestBody @Valid CreateWxCodeDto dto){
        try {
            //根据医院公钥和私钥获取医院信息
            HospitalInfo hospital = hospitalService.getHospitalByKey(new HospitalInfo() {{
                setServerKey(dto.getServerKey());
                setServerSecret(dto.getServerSecret());
            }});
            if(ObjectUtils.isEmpty(hospital)){
                throw new ServiceException("系统密钥错误,小程序码生成失败");
            }
            if(hospital.getRecordState().equals(0)){
                throw new ServiceException("医院未启用,小程序码生成失败");
            }


            byte[] bytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(dto.getScene(), dto.getPage(), dto.isCheckPath(), dto.getEnvVersion(), dto.getWidth(), dto.isAutoColor(), null, dto.isHyaline());
            //base64编码返回
            String encode = Base64.encode(bytes);
            return CommonResult.success(null,encode);
        } catch (WxErrorException e) {
            log.error("调用生成小程序码失败",e);
            throw new ServiceException("生成小程序码失败");
        }
    }
}
